package com.jhxy.algorithm.maxprofit;

import com.jhxy.algorithm.util.InputsForMaxProfit;
import com.jhxy.algorithm.util.PrintTool;

import java.util.List;

/**
 * 买卖股票的最佳时机：贪心算法
 */
public class GreedySolution {


    public static void main(String args[]) {
        InputsForMaxProfit inputs = new InputsForMaxProfit("1,2,3,4,5,6;7,1,5,3,6,4;7,6,4,3,1");
        PrintTool print = new PrintTool();
        GreedySolution ins = new GreedySolution();
        int i = 1;
        for (List<Object> input : inputs.inputs) {
            System.out.println("=================第" + (i++) + "组输入输出=================");
            print.printArray((int[]) input.get(0));
            int maxProfit = ins.maxProfit((int[]) input.get(0));
            System.out.println("");
            System.out.println(maxProfit);
            System.out.println("");
        }
    }

    /**
     * 使用贪心算法实现
     */
    private int maxProfit(int[] prices) {
        int maxProfit = 0;
        int minProfit = prices[0];

        for (int i = 1; i < prices.length; i++) {
            //局部的利润
            int profit = prices[i] - minProfit;
            if (profit > maxProfit) {
                maxProfit = profit;
            }

            if (prices[i] < minProfit) {
                minProfit = prices[i];
            }
        }

        return maxProfit;
    }
}
